Threads iii
A thread is a lightweight unit of execution within a program. It represents an independent path of execution. A Java program can have multiple threads running concurrently. For example, one thread can handle user input while another performs a calculation. The thread that starts the execution of a Java program is called the main thread.
There are two commonly taught ways to create a thread.
A. By Extending the Thread Class
Create a class that extends Thread and override its run() method.
B. By Implementing the Runnable Interface
Implement Runnable and provide the run() method.
This approach is generally preferred when the class already needs to extend another class, because Java does not support multiple inheritance of classes.
C. Using Lambda Expression
Since Runnable is a functional interface, we can write:
public class Demo {
public static void main(String[] args) {
Thread t = new Thread(() -> {
System.out.println("Thread is running");
});
t.start();
}
}
Although threads are useful, using multiple threads introduces several challenges.
Threads allow Java programs to perform multiple tasks concurrently, but shared resources must be managed carefully to avoid race conditions, data inconsistency, deadlocks, and excessive resource consumption.
join() makes the current thread wait until the specified thread finishes. join() does not start the thread. Since t has not been started, there is nothing for join() to wait for, so it returns immediately.
t1.start(); Starts the thread
isAlive(): Checks whether thread is alive. A Java thread returns false from isAlive() if it has not been started yet. Returns true only after the thread has been started and before it has terminated.
One important point: isAlive() does not mean the thread is currently executing. A thread that is sleeping or waiting can still return true.